package com.hrg.demo.controller;

import cn.hutool.core.date.DateUtil;
import com.dahuatech.icc.util.BeanUtil;
import com.hrg.demo.config.ImagesConfig;
import com.hrg.demo.entity.CaptureBo;
import com.hrg.demo.entity.RemoteCaptureResponse;
import com.hrg.demo.entity.RemoteCaptureResult;
import com.hrg.demo.entity.Result;
import com.hrg.demo.oss.PicDownloadDemo;
import com.hrg.demo.remoteCapture.RemoteCaptureDemo;
import com.hrg.demo.util.ImageProcessor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;

/**
 * @Author: zy
 * @Version: 1.0
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/api")
public class RemoteCaptureController {

    private final RemoteCaptureDemo remoteCaptureDemo;
    private final PicDownloadDemo picDownloadDemo;
    //private String path="D://images";
    private final ImagesConfig imagesConfig;


    @PostMapping("/capture")
    public Result<Object> capture(@RequestParam long id, @RequestParam String channelId){
        RemoteCaptureResponse remoteCaptureResponse = remoteCaptureDemo.remoteCapture(id,channelId);
        if(remoteCaptureResponse.getCode().equals("1000")) {
            RemoteCaptureResult captureResult = BeanUtil.toBean(remoteCaptureResponse.getData(), RemoteCaptureResult.class);
            String picInfo = captureResult.getParams().getPicInfo();
            System.out.println("远程设备抓图获取的图片信息： "+picInfo);
            log.info("远程设备抓图获取的图片信息：{}", picInfo);
            String imageFullPath=picDownloadDemo.getHttpsImageFullPath(picInfo);
            log.info("imageFullPath: {}",imageFullPath);
            picDownloadDemo.download(imageFullPath,imagesConfig.getImageBaseDir());
            return Result.success("成功",imagesConfig.getImageBaseDir()+"/"+imageFullPath);
        }

        return Result.error("失败");
    }

    @PostMapping("/captureImg")
    public Result<Object> captureImg(@Validated @RequestBody CaptureBo captureBo) throws IOException {
        log.info("captureBo:{}",captureBo);
        long id = captureBo.getId();
        String locationCode = captureBo.getLocationCode();
        String channelId = captureBo.getChannelId();
        RemoteCaptureResponse remoteCaptureResponse = remoteCaptureDemo.remoteCapture(id,channelId);
        if(remoteCaptureResponse.getCode().equals("1000")) {
            RemoteCaptureResult captureResult = BeanUtil.toBean(remoteCaptureResponse.getData(), RemoteCaptureResult.class);
            String picInfo = captureResult.getParams().getPicInfo();
            System.out.println("远程设备抓图获取的图片信息： "+picInfo);
            log.info("远程设备抓图获取的图片信息：{}", picInfo);
            String imageFullPath=picDownloadDemo.getHttpsImageFullPath(picInfo);
            log.info("远程 imageFullPath:{}",imageFullPath);
            try{

                Thread downloadThread = new Thread(() -> {
                    StopWatch stopWatch = new StopWatch();
                    stopWatch.start();
                    picDownloadDemo.download(imageFullPath, imagesConfig.getImageBaseDir());
                    stopWatch.stop();
                    log.info("下载图片耗时：{}", stopWatch.getTotalTimeMillis());
                });
                downloadThread.start();
                downloadThread.join(); // 等待线程执行完毕
                log.info("图片下载完成，继续执行");

            }catch (Exception e){
                log.error("下载图片错误！",e);
                e.printStackTrace();
            }
            try{
                String imageName = picInfo.substring(picInfo.lastIndexOf("/")+1);
                log.info("远程图片原文件名: {}",imageName);
                String localImagePathName = imagesConfig.getImageBaseDir()+"/"+imageName;
                log.info("本地图片完整路径文件名：{}",localImagePathName);
                String datePre = DateUtil.format(new Date(),"yyyyMMddHHmmss");
                String newName = datePre+"_"+locationCode;
                String targetPath = ImageProcessor.renameImageFile(localImagePathName, newName);
                log.info("新文件名路径:{}",targetPath);
                return Result.success("抓拍成功",targetPath);
            }catch (Exception e){
                log.error("重命名图片错误",e);
                e.printStackTrace();
            }
        }

        return Result.error("失败");
    }
}
